package com.jin.gulimall.product.web;

import com.jin.gulimall.product.entity.CategoryEntity;
import com.jin.gulimall.product.service.CategoryService;
import com.jin.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 因为要返回的是页面并不是数据，所以不要用@RestController,原因是不要用@ResquestBody
 */
@Controller
public class IndexController {
    @Autowired
    CategoryService categoryService;

    @Autowired
    RedissonClient redisson;

    @Autowired
    StringRedisTemplate redisTemplate;

    @GetMapping({"/","/index.html"})
    public String indexPage(Model model){
        //TODO: 查出所有商品的一级分类
        List<CategoryEntity> categoryEntities=categoryService.getLevel1Category();
        model.addAttribute("categories",categoryEntities);
        // 视图解析器进行拼串：classpath:/templates/+ 返回值 +.html
        return "index";
    }

    //index/catalog.json
    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<Catelog2Vo>> getCatelogJson() throws InterruptedException {
        Map<String, List<Catelog2Vo>> map=categoryService.getCatelogJson();
        return map;
    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        //1.获取一把锁，只要锁的名字一样，就是同一把锁
        RLock lock = redisson.getLock("my-lock");
        //加锁
        //lock.lock();//阻塞式等待。默认加的锁都是30s时间
        //锁的自动续期，如果业务超长，运行期间自动给锁续上新的30s,不用担心业务时间长，锁自动过期被删掉
        //加锁的业务只要运行完成，就不会给当前锁续期，即使不手动解锁，锁默认在30s以后自动删除
        //lock.lock(10, TimeUnit.SECONDS);//手动设置10s自动解锁，自动解锁时间一定要大于业务的执行时间
        //问题：lock.lock(10, TimeUnit.SECONDS)在锁时间到了以后，不会自动续期
        //1.如果我们传递了锁的超时时间，就发送给redis执行脚本，进行占锁，默认超时就是我们指定的时间
        //2.如果我们未指定锁的超时时间，就使用30*1000【LockWatchdogTimeout看门狗的默认时间】每隔10s都会自动续期
        //internalLockLeaseTime[看门狗时间]/3,10s
        //一般实际上还是用手动设置过期时间
        lock.lock(40, TimeUnit.SECONDS);
        try{
            System.out.println("加锁成功，执行业务..."+Thread.currentThread().getId());
            Thread.sleep(30000);
        }catch (Exception e){

        }finally {
            //3.解锁 就算解锁代码没有运行，redisson也不会出现死锁
            System.out.println("释放锁..."+Thread.currentThread().getId());
            lock.unlock();
        }
        return "hello";
    }

    @ResponseBody
    @GetMapping("/write")
    public String write(){
        RReadWriteLock lock = redisson.getReadWriteLock("rwLock");
        RLock rLock = lock.writeLock();
        String s="";
        try {
            rLock.lock();
            System.out.println("写锁加锁成功..."+Thread.currentThread().getId());
            s = UUID.randomUUID().toString();
            Thread.sleep(30000);
            redisTemplate.opsForValue().set("writeValue",s);
        }catch (Exception e){

        }finally {
            rLock.unlock();
        }

        return s;
    }

    @ResponseBody
    @GetMapping("/read")
    public String read(){
        RReadWriteLock lock = redisson.getReadWriteLock("rwLock");
        RLock rLock = lock.readLock();
        String s="";
        try {
            rLock.lock();
            System.out.println("读锁加锁成功..."+Thread.currentThread().getId());
            s = redisTemplate.opsForValue().get("writeValue");
        }catch (Exception e){

        }finally {
            rLock.unlock();
        }
        return s;
    }

    /**
     * 闭锁的演示
     * @return
     * @throws InterruptedException
     */
    @ResponseBody
    @GetMapping("/door")
    public String door() throws InterruptedException {
        RCountDownLatch lock = redisson.getCountDownLatch("door");
        lock.trySetCount(5);
        lock.await();
        return "放假了...";
    }

    @ResponseBody
    @GetMapping("/gogogo/{id}")
    public String gogogo(@PathVariable("id") Long id){
        RCountDownLatch lock = redisson.getCountDownLatch("door");
        lock.countDown();//计数减一
        return id + "班放假了...";
    }

    /**
     * 信号量演示(停车位模拟)
     */
    @ResponseBody
    @GetMapping("/park")
    public String park() throws InterruptedException {
        RSemaphore park = redisson.getSemaphore("park");
        //park.acquire();//获得一个车位
        boolean b = park.tryAcquire();
        return "ok=>"+b;
    }

    @ResponseBody
    @GetMapping("/go")
    public String go(){
        RSemaphore park = redisson.getSemaphore("park");
        park.release();//释放一个车位
        return "go...";
    }


}
